package com.itheima.tlais_web_management.aop;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tlais_web_management.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Pointcut("@annotation(com.itheima.tlais_web_management.aop.Log)")
    private void pt(){}

    @Around("pt()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        //获得令牌，解析令牌
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);

        //当前登录人 ID
        Integer id = (Integer) claims.get("id");

        //操作时间
        LocalDateTime now = LocalDateTime.now();

        //操作类名
        String classname = joinPoint.getTarget().getClass().getName();

        //操作方法名
        String methodname = joinPoint.getSignature().getName();

        //操作方法参数
        Object[] args = joinPoint.getArgs();
        String s = Arrays.toString(args);


        long begin = System.currentTimeMillis();

        Object proceed = joinPoint.proceed();

        long end = System.currentTimeMillis();

        //操作方法返回值
        String s1 = JSONObject.toJSONString(args);

        //操作时长
        long time = end - begin;

        log.info("登录人ID：" + id + "操作时间：" + now + "操作类名：" + classname + "操作方法名：" + methodname + "操作方法参数：" + s + "操作方法返回值：" + s1 + "操作时长：" + time );

        return proceed;

    }


}
